package org.hot100.h039;

import java.util.*;

/**
 * @Author: wjy
 * @Date: 2021/12/14 10:48
 */
public class Solution {

    public static void main(String[] args) {

        //int[] ints = {2, 3, 6, 7};
        int[] ints = {2,7,6,3,5,1};
        Solution solution = new Solution();
        List<List<Integer>> lists = solution.combinationSum(ints, 9);

        for (List<Integer> list : lists) {
            for (Integer i : list) {
                System.out.print(i);
            }
            System.out.println();
        }

    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates.length == 0) {
            return new LinkedList<>();
        }

        List<List<Integer>> res = new LinkedList<>();

        Arrays.sort(candidates);
        this.dfs(candidates.length, target, 0, res, new LinkedList<>(), candidates);

        return res;
    }

    public void dfs(int len, int target, int index, List<List<Integer>> res, LinkedList<Integer> temp, int[] candidates) {
        if (target == 0) {
            res.add(new LinkedList<>(temp));
            return;
        }

        for (int i = index; i < len; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            temp.add(candidates[i]);
            this.dfs(len, target - candidates[i], i, res, temp, candidates);
            temp.removeLast();
        }

    }

}
